<template>
   <vp-main-page @refresh="loadDataList">
	<template #search>
			<el-form label-suffix=":"  ref="searchFormRef" :model="searchForm" @submit.prevent @keyup.enter="loadDataList" label-width="120px">
				<vp-search-row :show-more="showMore">
					<vp-search-col>
						<el-form-item prop="bh">
							<template #label><vp-label zh="编号" en="No."  /></template>
							<el-input v-model="searchForm.bh" v-trim placeholder="" clearable></el-input>
						</el-form-item>
					</vp-search-col>
					<vp-search-col>
						<el-form-item prop="bt">
							<template #label><vp-label zh="标题" en="Title"  /></template>
							<el-input v-model="searchForm.bt" v-trim placeholder="" clearable></el-input>
						</el-form-item>
					</vp-search-col>
					<vp-search-col>
						<el-form-item prop="yxbs">
							<template #label><vp-label zh="是否有效" en="Valid" /></template>
							<el-select class="w100" v-model="searchForm.yxbs" clearable>
								<el-option :value="1" label="是/Yes"></el-option>
								<el-option :value="0" label="否/No"></el-option>
							</el-select>
						</el-form-item>
					</vp-search-col>
					<vp-search-col>
						<el-form-item prop="sxrq" >
							<template #label><vp-label zh="生效日期" en="Effective Date"/></template>
							<el-date-picker
								v-model="searchForm.sxrq"
								type="daterange"
								start-placeholder="开始日期/Start Date"
								end-placeholder="结束日期/End Date"
								value-format="YYYY-MM-DD"
								unlink-panels
								range-separator="-"
								style="width: 100%"
							>
							</el-date-picker>
						</el-form-item>
					</vp-search-col>
					<vp-search-col btn-col>
						<vp-btn-search :loading="loading" @click="handleSearch"/>
						<vp-btn-reset @click="handleSearchReset"/>
						<vp-btn-more @change="showMore = $event"/>
					</vp-search-col>
				</vp-search-row>
			</el-form>
		</template>
		<template #actions>
			<el-space>
				<vp-btn-add v-auth="'qualityManual.edit'"  @click="handleAdd"/>
			</el-space>
		</template>
		<template #table>
			<vp-table ref="tableRef" :data="flattenData" @sort-change="handleSortChange"  :span-method="objectSpanMethod"   stripe border  style="width: 100%" row-key="id">
				<el-table-column prop="xc" show-overflow-tooltip width="50" align="center">
					<template #header><vp-label zh="#" en=""/></template>
				</el-table-column>
				<el-table-column
					prop="yxbs" sortable="custom" 
					show-overflow-tooltip 
					:min-width="100"
					>
					<template #header><vp-label zh="状态" en="Status"/></template>
					<template #default="scope">
						{{scope.row.yxbs === 1? '有效/Valid' : (scope.row.yxbs===0 ? '无效/Invalid' : '')}}
					</template>
				</el-table-column>
				<el-table-column
					prop="lx" sortable="custom" 
					show-overflow-tooltip 
					:min-width="200"
					>
					<template #header><vp-label zh="文件类型" en="Doc. File"/></template>
					<template #default="scope">
						{{scope.row.lx === 10? '手册/Manual' : (scope.row.lx=== 20 ? '工作程序/Work Procedure' : '')}}
					</template>
				</el-table-column>
				<el-table-column prop="bh" sortable="custom"  show-overflow-tooltip :min-width="140">
					<template #header><vp-label zh="编号" en="No."/></template>
					<template #default="scope">
						<el-space >
							<span v-html="markTextColor(searchForm.bh, scope.row.bh)"/>
							<FilePopover :count="scope.row.fjcount"  :ywid ="scope.row.fjglid"></FilePopover>
						</el-space>
					</template>
				</el-table-column>
				<el-table-column prop="bc" show-overflow-tooltip :min-width="80">
					<template #header><vp-label zh="版次" en="Edition"/></template>
				</el-table-column>
				<el-table-column prop="bt" sortable="custom"  show-overflow-tooltip :min-width="200">
					<template #header><vp-label zh="标题" en="Title"/></template>
					<template #default="scope">
						<span v-html="markTextColor(searchForm.bt, scope.row.bt)"/>
					</template>
				</el-table-column>
				<el-table-column  prop="sxrq" show-overflow-tooltip :min-width="140">
					<template #header><vp-label zh="生效日期" en="Effective Date"/></template>
				</el-table-column>
				<el-table-column   :min-width="260"  show-overflow-tooltip align="center">
					<template #header><vp-label zh="表格" en="Table"/></template>
					<el-table-column  show-overflow-tooltip :min-width="200">
						<template #header><vp-label zh="编号" en="No."/></template>
						<template #default="scope">
							<el-space>
								<span >{{ scope.row.subBh}}</span> 
								<FilePopover :count="scope.row.subFjcount"  :ywid ="scope.row.subFjglid"></FilePopover>
							</el-space>
						</template>
					</el-table-column>
					<el-table-column prop="subBc" show-overflow-tooltip :min-width="80">
						<template #header><vp-label zh="版次" en="Edition"/></template>
					</el-table-column>
					<el-table-column prop="subBt"  show-overflow-tooltip :min-width="200">
						<template #header><vp-label zh="标题" en="Title"/></template>
					</el-table-column>
					<el-table-column  prop="subSxrq" show-overflow-tooltip :min-width="140">
						<template #header><vp-label zh="生效日期" en="Effective Date"/></template>
					</el-table-column>
					<el-table-column :label="$t('item.operations')" fixed="right" width="100">
						<template #header>
							<vp-label-operations/>
						</template>
						<template #default="scope">
							<vp-btn text type="primary" v-if="scope.row.subId" v-auth="'qualityManual.edit'" @click="handleEdit(scope.row.subId)"><vp-label zh="修订" en="Revision"/></vp-btn>
						</template>
					</el-table-column>
				</el-table-column>
				<el-table-column :label="$t('item.operations')" fixed="right" width="100">
					<template #header>
						<vp-label-operations/>
					</template>
					<template #default="scope">
						<el-space>
							<vp-btn v-if="scope.row.yxbs == 1" text type="primary" v-auth="'qualityManual.edit'" @click="handleEdit(scope.row.id)"><vp-label zh="修订" en="Revision"/></vp-btn>
						</el-space>
					</template>
				</el-table-column>
			</vp-table>
		</template>
		<EditQualityManual ref="editRef" @formSubmited="handleFormSubmited"></EditQualityManual>
	</vp-main-page>
</template>
<script setup lang="ts" name="list">
import { defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import request from '/@/utils/request';
import { markTextColor } from '/@/utils/toolsValidate';

const FilePopover = defineAsyncComponent(() => import('/@/components/vp/file/VpFilePopover.vue'));
const EditQualityManual = defineAsyncComponent(() => import('./component/EditQualityManual.vue'));

	const tableData = ref([]);
	const loading = ref(false);
	const editRef = ref();
	const showMore = ref(false);
	const searchForm = reactive({
		bh: "",
		bt: "",
		yxbs: null,
		sxrq: [],
	});

	 // 扁平化后的数据
	 const flattenData = ref([] as any);
      // 合并配置（记录每行需要合并的数量）
	  const spanArr = ref([] as any);
		
	const loadDataList = () => {
		loading.value = true;
		request.get('/quality/manual/list', {
			params: {
				...searchForm,
			}
		}).then(res => {
			tableData.value = res?.data || [];
			flattenData.value = [];
			spanArr.value = [];

			tableData.value.forEach((parent: any, index:number)=> {
				let xc = 1;
				 // 处理没有子级的情况
				 const childCount = parent.tables ? parent.tables.length : 0;
				// 父行需要合并的行数 = 子行数量 + 1（父行自己）
				const rowspan = childCount > 0 ? childCount : 1;
				// 添加父行数据
				const parentRow = {
					...parent,
					xc: (index + 1),
					isParent: true,
					rowspan: rowspan,
				};
				if(childCount > 0){
					parentRow.subBh= parent.tables[0].bh;
					parentRow.subBt= parent.tables[0].bt;
					parentRow.subSxrq= parent.tables[0].sxrq;
					parentRow.subBc= parent.tables[0].bc;
					parentRow.subFjglid= parent.tables[0].fjglid;
					parentRow.subFjcount= parent.tables[0].fjcount;
					parentRow.subId= parent.tables[0].id;
				}
				
				flattenData.value.push(parentRow);
				spanArr.value.push(rowspan); // 父行需要合并的行数
				
				// 添加子行数据
				if (childCount > 1) {
					for (let i = 1; i < childCount; i++) {
						const child = parent.tables[i];
						flattenData.value.push({
							parentId: parent.id,
							isParent: false,
							// 标记为剩余子行
							subBh: child.bh,
							subBt: child.bt,
							subSxrq: child.sxrq,
							subBc: child.bc,
							subFjglid: child.fjglid,
							subFjcount: child.fjcount,
							subId: child.id
						});
						spanArr.value.push(0); // 子行标记为0（不显示）
          			}	
				}
			});
		}).finally(()=>{
			loading.value = false;
		})	
	}

	const searchFormRef = ref();

	const handleSearch = ()=>{
		loadDataList();
	}
	const handleSearchReset = ()=>{
		searchFormRef.value.resetFields();
	}
	const handleSortChange = (column: any)=>{
		loadDataList();
	}
	onMounted(() => {
		loadDataList();
	})

	const handleFormSubmited = () =>{
		loadDataList();
	}

	const handleAdd = () => {
		editRef.value.handleOpen("", "add");
	}

	const handleEdit = (id: any) =>{
		editRef.value.handleOpen(id, "revision");
	}

	const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) =>{
		if(tableData.value && tableData.value.length>0){
			if (columnIndex === 0 || columnIndex === 1|| columnIndex === 2|| columnIndex === 3|| columnIndex === 4|| columnIndex === 5 || columnIndex === 6 || columnIndex === 12) {
				// 当前行需要合并的行数
				const rowspan = spanArr.value[rowIndex];
				// 当前行需要合并的列数
				const colspan = rowspan > 0 ? 1 : 0;
				return {
					rowspan: rowspan,
					colspan: colspan
				};
			}
			
			// 后两列（子表格字段）不合并
			return {
				rowspan: 1,
				colspan: 1
			};
		}
	}
	

</script>
